<template>
    <div class="sys-org-container">
        

            <div style="width: 100%;">
                <screeningCondition :inquireInfo="state.inquireInfo" @getChildren="getData">
                    <el-button type="primary" icon="ele-Plus" @click="openAddPos" v-auth="'sysOrg:add'">
                        新增
                    </el-button>
                </screeningCondition>
            </div>

            <el-card class="full-table" shadow="hover" style="margin-top: 5px">
                <el-table :data="state.Data" style="width: 100%" v-loading="state.loading" border highlight-current-row
                    :header-cell-style="{
                        background: 'var(--el-color-primary)',
                        height: '55px', color: '#fff', border: '1px solid #fff', fontWeight: 'bold', fontSize: '13px'
                    }" :cell-style="{ padding: '2px' }">
                    <el-table-column type="expand">
                        <template #default="props">
                            <div m="4">
                                <el-table :data="props.row.subTempDetail" align="left" :style="{ paddingLeft: '70px' }">
                                    <el-table-column label="模板号" width="200" prop="ModelNo" align="center" />
                                    <el-table-column label="子任务序号" width="200" prop="subTaskSeq" align="center" />
                                    <el-table-column label="能否重复执行" width="200" prop="deduplicate" align="center">
                                        <template v-slot="scope">
                                            <el-switch v-model="scope.row.deduplicate" class="ml-2"
                                                style="--el-switch-on-color:var(--el-color-primary); --el-switch-off-color: #bbb"
                                                disabled />
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="模板号" prop="wcsTemLogicNo" align="center" />
                    <el-table-column label="模板名称" prop="wcsTemlogicName" align="center" />
                    <el-table-column label="操作" fixed="right" width="150" align="center" show-overflow-tooltip>
                        <template #default="scope">
                            <el-button size="small" type="primary" @click="openEditPos(scope.row)"> 编辑
                            </el-button>
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)"
                                v-auth="'warehouse:delete'"> 删除 </el-button>
                            <!-- <el-button size="small" text type="primary" @click="handleOpenRelation(scope.row)"
									> 区域管理 </el-button> -->
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination v-model:current-page="state.queryParams.page"
                    v-model:page-size="state.queryParams.pageSize" :page-sizes="[10, 20, 30, 40]"
                    layout="->,total, sizes, prev, pager, next, jumper" :total="state.total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" :small="true" />
            </el-card>


        <el-drawer v-model="editDrawer" title="编辑模板" :append-to-body="true" size="30%">
            <el-form :model="state.ruleForm" ref="editRuleFormRef" label-width="auto" class="fl">
                <el-form-item label="编号" prop="wcsTemLogicNo"
                    :rules="[{ required: true, message: '编号不能为空', trigger: 'blur' }]" align="center">
                    <el-input v-model="state.ruleForm.wcsTemLogicNo" placeholder="模板编号" clearable class="input"
                        disabled />
                </el-form-item>
                <el-form-item label="名称" prop="wcsTemlogicName"
                    :rules="[{ required: true, message: '编号不能为空', trigger: 'blur' }]" align="center">
                    <el-input v-model="state.ruleForm.wcsTemlogicName" placeholder="模板名称" clearable class="input" />
                </el-form-item>
                <el-row>
                    <el-col :span="8">
                        <span style="font-size: 12px;">子任务名称</span>
                    </el-col>
                    <el-col :span="8">
                        <span style="font-size: 12px;">重复执行</span>
                    </el-col>
                    <el-col :span="8">
                        <el-icon @click="addEdit">
                            <Plus />
                        </el-icon>
                    </el-col>
                </el-row>
                <el-form-item>
                    <div v-for="(item, index) in state.ruleForm.subTempDetail" :key="item.ModelNo">
                        <el-row>
                            <el-col :span="8">
                                <el-input type="text" v-model="item.ModelNo" placeholder="输入任务内容"
                                    @input="updateInput(index, $event.target.value)" @click="openEditComponent(index)"
                                    style="display: inline" clearable @clear="removeEdit(index)" />
                            </el-col>
                            <el-col :span="8">
                                <el-switch v-model="item.deduplicate"
                                    style="--el-switch-on-color: var(--el-color-primary); --el-switch-off-color: #bbb" />
                            </el-col>
                            <el-col :span="8"></el-col>
                        </el-row>
                    </div>
                </el-form-item>

            </el-form>

            <div style="width: 100%;display: flex;justify-content: center;margin-top:60px">
                <el-button @click="submitEdit" type="primary" round style="width:80px;height:30px">确认</el-button>
                <el-button @click="editDrawer = false" round style="width:80px;height:30px">取消</el-button>
            </div>
        </el-drawer>
        <el-drawer v-model="addDrawer" title="新增模板" :append-to-body="true" size="30%">
            <el-form :model="state.ruleForm2" ref="ruleFormRef" label-width="auto" class="fl">
                <el-form-item label="编号" prop="wcsTemLogicNo"
                    :rules="[{ required: true, message: '编号不能为空', trigger: 'blur' }]" align="center">
                    <el-input v-model="state.ruleForm2.wcsTemLogicNo" placeholder="模板编号" clearable class="input" />
                </el-form-item>
                <el-form-item label="名称" prop="wcsTemlogicName"
                    :rules="[{ required: true, message: '编号不能为空', trigger: 'blur' }]" align="center">
                    <el-input v-model="state.ruleForm2.wcsTemlogicName" placeholder="模板名称" clearable class="input" />
                </el-form-item>
                <el-row>
                    <el-col :span="8" class="center-align">
                        <span style="font-size: 12px;">子任务名称</span>
                    </el-col>
                    <el-col :span="8" class="center-align">
                        <span style="font-size: 12px;">重复执行</span>
                    </el-col>
                    <el-col :span="8" class="center-align">
                        <el-icon @click="addInput">
                            <Plus />
                        </el-icon>
                    </el-col>
                </el-row>
                <el-form-item>
                    <div v-for="(item, index) in state.ruleForm2.subTempDetail" :key="item.ModelNo">
                        <el-row>
                            <el-col :span="8" class="center-align">
                                <el-input type="text" v-model="item.ModelNo" placeholder="输入任务内容"
                                    @input="updateInput(index, $event.target.value)" @click="openEditComponent(index)"
                                    style="display: inline" clearable @clear="removeInput(index)" />
                            </el-col>
                            <el-col :span="8" class="center-align">
                                <el-switch v-model="item.deduplicate"
                                    style="--el-switch-on-color: var(--el-color-primary); --el-switch-off-color: #bbb" />
                            </el-col>
                            <el-col :span="8" class="center-align"></el-col>
                        </el-row>

                    </div>
                </el-form-item>
            </el-form>

            <div style="width: 100%;display: flex;justify-content: center;margin-top:60px">
                <el-button @click="submit" type="primary" round style="width:80px;height:30px">确认</el-button>
                <el-button @click="addDrawer = false" round style="width:80px;height:30px">取消</el-button>
            </div>
        </el-drawer>

        <EditPos ref="editPosRef" :title="state.editPosTitle" @handleQuery="getData" />

    </div>
</template>
<script lang="ts" setup name="Warehouse">
import { onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import editRCSModel from "/@/views/system/wcsModel/editRCSModel.vue";

import screeningCondition from '/@/views/tools/screeningCondition.vue'
import EditPos from '/@/views/system/wcsModel/component/editPos.vue';

import { WcsApi, WmsApi } from '/@/api/wh';
//用于添加模板子模板的子组件
const subEditComponent = ref()
const addDrawer = ref(false);
const editDrawer = ref(false);
const editPosRef = ref()
const editRuleFormRef = ref()
const ruleFormRef = ref()
const state = reactive({
    editPosTitle: '',
    isEditing: false,
    a: undefined,
    loading: false,
    Data: [],
    queryParams: {
        wcsTemLogicNo: "",
        wcsTemlogicName: undefined,

        page: 1,
        pageSize: 20,
    },
    dataonLineListSelections: [],
    editOrgTitle: '',
    belongWarehouses: [],
    relationTitle: '',
    //编辑对象
    ruleForm: {
        "wcsTemlogicName": undefined,
        "wcsTemLogicNo": undefined,
        "subTempDetail": [
            {
                ModelNo: '',
                ModelName: '',
                deduplicate: false,
                subTaskSeq: 1
            } // 初始的 input 框的值  
        ]
    },
    //新增对象
    ruleForm2: {
        "wcsTemlogicName": undefined,
        "wcsTemLogicNo": undefined,
        "subTempDetail": [
            {
                ModelNo: '',
                ModelName: '',
                deduplicate: false,
                subTaskSeq: 1
            } // 初始的 input 框的值  
        ]
    },
    id: 0,
    inquireInfo: [
        {
            label: "模板编号",
            value: "",
            key: "wcsTemLogicNo",
            options: [],
            type: 'input'
            //待让后端做分页
        },
        {
            label: "模板名称",
            value: "",
            key: "wcsTemlogicName",
            options: [],
            type: 'input'

        }
    ],


    previousCondition: {},
    total: 0,
    editTitle: '',


});
onMounted(() => {
    getData(state.queryParams)
    //请求接口获得模态框中类型列表的数据，赋值给orgTypeList=orgData

})
// 打开自组件
const openEditComponent = (index: number) => {
    state.editTitle = "选择RCS模板";
    subEditComponent.value.openDialog();

}
// 打开新增页面
const openAddPos = () => {
    state.editPosTitle = '添加WCS模板';
    //父传子
    editPosRef.value?.openDialog(state.ruleForm2);
};

// 打开编辑页面
const openEditPos = (row: any) => {
    state.isEditing = true;
    state.editPosTitle = '编辑WCS模板';
    editPosRef.value?.openDialog(row, state.isEditing);
};
const handleOpenEdit = (row: any) => {
    //改变第二个被赋值的内容，不会影响第一个赋值的内容，是一种浅拷贝
    state.ruleForm = Object.assign({}, row);
    //父组件调用子组件的方法
    editDrawer.value = true;
    state.isEditing = true;
    console.log(state.ruleForm);
}
const handleDelete = (row: { whName: any; wcsTemLogicNo: object; }) => {

    ElMessageBox.confirm(`确定删除该仓库：【${row.wcsTemlogicName}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            console.log(typeof row.wcsTemLogicNo);

            await WmsApi().delWcsModel(row.wcsTemLogicNo)
                .then(function (res) {
                    console.log(res);

                    ElMessage.success('删除成功');
                    getData(state.queryParams);
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        });
}
const addInput = () => {
    state.ruleForm2.subTempDetail.push({ ModelNo: '' });
}
const addEdit = () => {
    state.ruleForm.subTempDetail.push({ ModelNo: '' });
    console.log(state.ruleForm.subTempDetail.length);

}
const removeInput = (index: number) => {
    if (index > -1) { // 确保不会删除未定义的索引  
        state.ruleForm2.subTempDetail.splice(index, 1);
        console.log(state.ruleForm2.subTempDetail);

    }
}
const removeEdit = (index: number) => {
    if (index > -1) { // 确保不会删除未定义的索引  
        state.ruleForm.subTempDetail.splice(index, 1);
        console.log(state.ruleForm2.subTempDetail);

    }
}
const updateInput = (index: number, value: any) => {
    // 直接修改数组中的对象属性，Vue 3 会自动追踪变化  
    state.ruleForm2.subTempDetail[index].ModelNo = value;
    // 这里也可以添加逻辑来处理或保存输入的值  
    console.log(`输入的值：${value}`);
};
const currentRow = ref()
const addModelNoValue = (info: any) => {
    //把选择的子模板号传给对象，把名称传给页面用于显示

    console.log(info);
    if (state.isEditing) {
        state.ruleForm.subTempDetail[state.ruleForm.subTempDetail.length - 1].ModelNo = info[0].modelProcessCode
        state.ruleForm.subTempDetail[state.ruleForm.subTempDetail.length - 1].ModelName = info[0].temlogicName

    } else {


        state.ruleForm2.subTempDetail[state.ruleForm2.subTempDetail.length - 1].ModelNo = info[0].modelProcessCode
        state.ruleForm2.subTempDetail[state.ruleForm2.subTempDetail.length - 1].ModelName = info[0].temlogicName
    }

}

const getData = async (value: any) => {
    //把用户输入的条件保存下来
    state.previousCondition = value
    if (value) {
        state.queryParams.wcsTemLogicNo = value.wcsTemLogicNo;
        state.queryParams.wcsTemlogicName = value.wcsTemlogicName;
    }


    await WcsApi().checkModel(state.queryParams)
        .then(function (res) {
            state.Data = res.data.result.items;
            console.log(state.Data);

            state.total = res.data.result.total;
        })
        .catch(function (error) {
            console.log(error);
        });
}

const submit = () => {
    ruleFormRef?.value.validate(async (valid, object) => {
        if (!valid) return false;
        //处理子序列的编号
        state.ruleForm2.subTempDetail.forEach((item, index) => {
            item.subTaskSeq = index + 1
        })
        console.log(state.ruleForm2);

        WmsApi().addWcsModel(state.ruleForm2)
            .then(function (res) {
                ElMessage.success('新增成功');
                getData(state.queryParams);
            })
            .catch(function (error) {
                console.log(error);

            });

        addDrawer.value = false;

    });
}
const submitEdit = () => {
    editRuleFormRef?.value.validate(async (valid, object) => {
        if (!valid) return false;
        console.log(state.ruleForm);
        //处理子序列的编号
        state.ruleForm.subTempDetail.forEach((item, index) => {
            item.subTaskSeq = index + 1
        })
        await WmsApi().ModifyWcsModel(state.ruleForm)
            .then(function (res) {
                ElMessage.success('修改成功');
                getData(state.queryParams);
                state.isEditing = false;
            })
            .catch(function (error) {
                console.log(error);

            });
        editDrawer.value = false;
    });
}
// 打开编辑页面
const openEdit = (row) => {

    editDrawer.value = true;
    state.ruleForm = row;

};
const deleteOne = (row) => {
    let that = this;
    ElMessageBox.confirm(`确定删除该区域：【${row.wcsTemlogicName}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            console.log(row);

            await WmsApi().modelPageDelete(row.id)
                .then(function (res) {
                    ElMessage.success('删除成功');
                    getData(state.queryParams);
                })
        })
        .catch((error) => {
            console.log(error);

            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        });
};
const handleSizeChange = (val) => {
    state.queryParams.wcsTemLogicNo = state.previousCondition.wcsTemLogicNo;
    state.queryParams.wcsTemlogicName = state.previousCondition.wcsTemlogicName;
    state.queryParams.holdingPoint = state.previousCondition.holdingPoint;
    state.queryParams.pageSize = val;
    getData(state.queryParams);
};
const handleCurrentChange = (newVal) => {
    state.queryParams.wcsTemLogicNo = state.previousCondition.wcsTemLogicNo;
    state.queryParams.wcsTemlogicName = state.previousCondition.wcsTemlogicName;
    state.queryParams.holdingPoint = state.previousCondition.holdingPoint;
    state.queryParams.pageNum = newVal;
    getData(state.queryParams);
};

const delOrg = (row) => {


};


</script>
<style lang="scss" scoped>
.lie .el-form-item {
    margin-bottom: 30px;
    font-size: 16px;
}

.fl {
    /* // padding: 20px; */
    width: 60%;
    margin: 20px 80px;

}

.hang {
    display: flex;
}

.radius {
    height: 22px;
    width: 164.75px;
    border: 1px solid var(--el-border-color);
    border-radius: 5px;
    background-color: #ddd;
    padding-left: 5px;
    padding-top: -4px;
    color: #afabb9;
    background-color: #f5f7fa;
    /*    margin-top: 20px; */
}

.container {
    margin-top: 15px;
    width: 100%;
    display: flex;
    flex-direction: column;
    height: calc(100% - 82px);
}

.table {
    width: 100%;
    flex: 1;
    height: 100%;
}

.el-table {
    width: 100%;
}

.extra {
    width: 170px;
    height: 80px;

    :deep(.el-textarea__inner) {
        height: 80px;
    }
}

.center-align {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    /* 如果你还想让 span 内的文本垂直居中（对于单行文本），可以添加 */
    text-align: center;
}
</style>